/**
 * Created by 丶龟 on 2017/8/25.
 */

"use strict";

//=============
// 引入程序依赖
//=============
import React, { Component } from 'react' ;
import { connect } from 'react-redux' ;
import { Link, browserHistory } from 'react-router' ;
import NetworkEngine from '../../../utils/NetworkEngine' ;
import UrlManager from '../../../utils/UrlManager' ;
import { mapStateToProps, mapDispatchToProps } from './MobileHomeRedux';
import HomeList from "./HomeGroup/HomeList";

import Header from "../../../components/Public/Header/Header"

var weixinUrl = location.href.split('#')[0];
class MobileHomeContainer extends Component{
    constructor(props){
        super(props) ;
        this.state={
            pageSize:1,
            visibile:0,
            list:[],
        }
    }

    componentWillMount() {
        this.great();
    }

    componentDidMount() {
        $(".mobile-home").css("border-bottom",".08rem solid #f7ca0f");
        $(".mobile-home").css("color","#111111");
        $(".mobile-home").css("font-weight","500");
        $(".mobile-demand").css("border-bottom",".08rem solid #fff");
        this.list();
        let id = sessionStorage.getItem('id');
        if (id == null) {
            $(this.refs.height).css("bottom","1.35rem");
        } else {
            $(this.refs.height).css("bottom","0");
            $(this.refs.height).css("overflow-y","visible");
        }
    }

    //初始化首页信息
    initialHome() {
        this.state.visibile=2;
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.mobileHome(),
            {
                pageNum:this.state.pageSize,
                userKeyId:sessionStorage.getItem("userKeyId")
            }
        ).then(
            data => {
                // let _data = data.data.data;
                // this.props.initialHome(_data);
                let list = this.state.list;
                function isEmptyObject(e) {
                    if(e.length == 0){
                        return true;
                    }else{
                        return false;
                    }
                    // var t;
                    // for (t in e)
                    //     return !1;
                    // return !0
                }
                if(isEmptyObject(data.data.data.list)){
                    // if(this.state.pageSize>1){
                    //     $(this.refs.nullList).show();
                    //     $(this.refs.more).hide();
                    //     this.setState({
                    //         visibile: 5,
                    //     }) ;
                    // }else{
                    //     this.props.creatorChange(list) ;
                    //     $(this.refs.nullList).show();
                    //     $(this.refs.more).hide();
                    // }
                    // this.props.creatorChange(list) ;
                    $(this.refs.nullList).show();
                    $(this.refs.more).hide();
                }else {
                    $(this.refs.nullList).hide()
                    let datas = data.data.data.list;
                    for (var i = 0; i < datas.length; i++) {
                        list.push(datas[i]);
                    }
                    this.props.initialHome(list) ;
                    this.setState({
                        pageSize: this.state.pageSize + 1,
                        visibile: 0,
                        list: list,
                    })
                    $(this.refs.more).show();
                    if(data.data.data.length<10){
                        $(this.refs.more).hide();
                    }
                }
            }
        ).catch(
            err => {
            }
        )
    }

    list() {
        var url = window.location.href;
        if (url.indexOf("?") > -1) {
            window.location.href = url.split("?")[0];
            return;
        }
        weixinUrl = weixinUrl.replace(/\//g, '_');
        let urlManager = new UrlManager();
        NetworkEngine(
            "get",
            urlManager.shareWeiXin() + "/" + weixinUrl,
        ).then(
            data => {
                this.shareSuccess(data.data)
            }
        ).catch(
            err => {
            }
        )
    }

    shareSuccess(data) {
        let _this = this;
        let title = _this.state.title;
        let videoImgUrl = _this.state.videoImgUrl;
        let des = _this.state.introduction;
        let videoUrl = window.location.href;
        /*---------------微信分享------------------*/
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: 'wxae5b39ca398c9f2f', // 必填，公众号的唯一标识
            // appId: 'wx4002b019d6429df6', // 必填，公众号的唯一标识
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature,// 必填，签名，见附录1
            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(function () {
            // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
            console.log("title:" + _this.state.title);
            console.log("VideoUrl:" + videoUrl);
            console.log("videoImgUrl:" + videoImgUrl);

            let that = _this;
            wx.onMenuShareTimeline({
                title: data.title, // 分享标题
                link: data.videoUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                //imgUrl: localStorage.getItem("videoImg"), // 分享图标
                imgUrl: data.videoImgUrl, // 分享图标
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
            wx.onMenuShareAppMessage({
                title: data.title, // 分享标题
                desc: data.des, // 分享描述
                link: data.videoUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: data.videoImgUrl, // 分享图标
                type: 'link', // 分享类型,music、video或link，不填默认为link
                dataUrl: data.videoUrl, // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
        });
        wx.error(function (res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        });
    }

    great(){
        if(this.state.visibile==0) {
            this.initialHome();
        }
    }

    //进入个人主页
    queryCreator() {
        console.log("======userId======",sessionStorage.getItem("id"));
        localStorage.setItem("personalId",sessionStorage.getItem("id"))
        // var id = sessionStorage.getItem("id").replace(/\//g, '_');
        var id = sessionStorage.getItem("id");
        var viewerKey = sessionStorage.getItem("viewerKey");
        if(viewerKey == null || viewerKey == ""){
            viewerKey = "0";
        }

        browserHistory.push("/App/MobileMine/"+id+"/"+viewerKey);
        window.scrollTo(0,0);
    }

    render(){
        console.log("zzzzzz",this.props.homeList)
        return(
            <div>
                <div className="h5-wrapper"  ref="height">
                    {/*<header className="h5-header">*/}
                        {/*<img src={logo} alt="咪吱logo" className="logo" />*/}
                        {/*{*/}
                            {/*(sessionStorage.getItem('id')) ?*/}
                                {/*<img src={sessionStorage.getItem("headUrl").length>4 ? sessionStorage.getItem("headUrl"):head}  className="head" onClick={this.queryCreator.bind(this)} />*/}
                                {/*:<div></div>*/}
                        {/*}*/}
                    {/*</header>*/}
                    <Header/>
                    <div className="h5-content">

                        {/*<div className="h5-act">*/}
                        {/*<img src={this.props.homeList.campaign.imgUrl} alt="活动海报"/>*/}
                        {/*<p className="tips">活动</p>*/}
                        {/*</div>*/}

                        <div className="h5-editor">
                            <div className="editor-title">编辑精选<span>Editor selection</span></div>
                            {
                                this.props.homeList.map((data, i) => {
                                    return <HomeList
                                        key={i}
                                        filmId={data.filmId}
                                        nickName={data.nickName}
                                        likeNum={data.likeNum}
                                        title={data.title}
                                        videoImgUrl={data.videoImgUrl}
                                        videoLength={data.videoLength}
                                        views={data.views}
                                        commentNum={data.commentNum}
                                        type={data.type}
                                        categoryName={data.categoryName}
                                        filmNum={data.filmNum}
                                        fansNum={data.fansNum}
                                        autograph={data.autograph}
                                        headUrl={data.headUrl}
                                        userId={data.userId}
                                        typeOfData={data.typeOfData}
                                    />
                                })
                            }
                        </div>
                        <div ref="nullList" className="m-tip" style={{display:"none"}}>没有更多数据</div>
                        <div ref="more" className="more-btn" style={{display:"none"}} onClick={this.great.bind(this)}>加载更多</div>
                    </div>
                </div>
                {
                    (sessionStorage.getItem('id'))?<link></link>:<Link to="/Login"><button className="join-us orange-btn">加入我们</button></Link>
                }
            </div>
        )
    }
}

const MobileHome = connect(mapStateToProps, mapDispatchToProps)(MobileHomeContainer) ;

export { MobileHome as default } ;
